package tas.co.in.daoimpl.login;

import java.io.StringWriter;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.xml.transform.OutputKeys;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.Transformer;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

import tas.co.in.dao.login.LoginConnect;
import tas.co.in.domain.logindomain.LoginInfoBean;

public class LoginImpl extends SqlMapClientDaoSupport implements LoginConnect {

	public LoginInfoBean validateLoginDetails(LoginInfoBean infoBean) {

		return (LoginInfoBean) getSqlMapClientTemplate().queryForObject(
				"loginDetails.validateuserdetails", infoBean);
	}

	public LoginInfoBean getLoginUser(LoginInfoBean infoBean) {

		int result;

		try {
			result = getSqlMapClient().update("loginDetails.updatelogintime",
					infoBean);

			if (result == 1) {
				return (LoginInfoBean) getSqlMapClientTemplate()
						.queryForObject("loginDetails.getuserinfo", infoBean);
			}

		} catch (SQLException e) {

			System.out.println(e);
			;
		}

		return null;
	}

	/**
	 * This method will generate XML for the menu
	 * 
	 * @param login
	 *            , object of the Login
	 * @return StringWriter containing the generated XML
	 */
	@SuppressWarnings( { "unchecked" })
	public StringWriter getMenu(LoginInfoBean login) {

		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		DocumentBuilder builder;
		Document doc = null;
		Element rootElement = null;
		StringWriter sw = null;
		// logObj.info("getMenu");

		try {
			builder = factory.newDocumentBuilder();
			doc = builder.newDocument();
			rootElement = doc.createElement("menuList");
			doc.appendChild(rootElement);

		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		}

		List<String> createdElement = new ArrayList<String>();
		List<Element> elementList = new ArrayList<Element>();
		String errorMenu = null;
		try {
			List<LoginInfoBean> authorizdMenu = getSqlMapClientTemplate()
					.queryForList("loginDetails.getAuthorizedMenuItem", login);

			int index = 0;
			int maxLengthMenuId = 0;
			for (int i = 0; i < authorizdMenu.size(); i++) {
				for (int j = 2; j <= authorizdMenu.get(i).getMenuId().length(); j++) {
					LoginInfoBean loginObj = new LoginInfoBean();
					loginObj.setMenuId(authorizdMenu.get(i).getMenuId()
							.substring(0, j));
					errorMenu = authorizdMenu.get(i).getMenuId()
							.substring(0, j);
					List<LoginInfoBean> menuDetail = getSqlMapClientTemplate()
							.queryForList("loginDetails.getMenuDetail",
									loginObj);
					boolean check = checkDuplicateElement(createdElement,
							menuDetail.get(0).getMenuId());
					if (!check) {
						Element element = doc.createElement("menuItem");
						element.setAttribute("menuId", menuDetail.get(0)
								.getMenuId());
						element.setAttribute("menuName", menuDetail.get(0)
								.getMenuName());

						if (menuDetail.get(0).getMenuId().length() > maxLengthMenuId) {
							maxLengthMenuId = menuDetail.get(0).getMenuId()
									.length();
						}

						elementList.add(element);
						createdElement.add(menuDetail.get(0).getMenuId());
						index++;
					}
				}
			}
		} catch (java.lang.IndexOutOfBoundsException e) {
			System.out
					.println("Menu Fail due to ("
							+ errorMenu
							+ ") menu item entry missing in code_allotment table in database");
			System.out.println(e.getMessage());
			sw = new StringWriter();
			sw.write("errorMenu:" + errorMenu);
			return sw;
		}

		// logic to add created node into XML doc
		for (int m = 0; m < elementList.size(); m++) {

			if (elementList.get(m).getAttribute("menuId").length() == 6) {
				int itemPosition = searchElement(elementList, elementList
						.get(m).getAttribute("menuId").substring(0, 2));
				int itemPosition1 = searchElement(elementList, elementList.get(
						m).getAttribute("menuId").substring(0, 3));
				int itemPosition2 = searchElement(elementList, elementList.get(
						m).getAttribute("menuId").substring(0, 4));
				int itemPosition3 = searchElement(elementList, elementList.get(
						m).getAttribute("menuId").substring(0, 5));
				elementList.get(itemPosition).appendChild(
						elementList.get(itemPosition1)).appendChild(
						elementList.get(itemPosition2)).appendChild(
						elementList.get(itemPosition3)).appendChild(
						elementList.get(m));
				rootElement.appendChild(elementList.get(itemPosition));
			}
			if (elementList.get(m).getAttribute("menuId").length() == 5) {
				int itemPosition = searchElement(elementList, elementList
						.get(m).getAttribute("menuId").substring(0, 2));
				int itemPosition1 = searchElement(elementList, elementList.get(
						m).getAttribute("menuId").substring(0, 3));
				int itemPosition2 = searchElement(elementList, elementList.get(
						m).getAttribute("menuId").substring(0, 4));
				elementList.get(itemPosition).appendChild(
						elementList.get(itemPosition1)).appendChild(
						elementList.get(itemPosition2)).appendChild(
						elementList.get(m));
				rootElement.appendChild(elementList.get(itemPosition));
			}
			if (elementList.get(m).getAttribute("menuId").length() == 4) {
				int itemPosition = searchElement(elementList, elementList
						.get(m).getAttribute("menuId").substring(0, 2));
				int itemPosition1 = searchElement(elementList, elementList.get(
						m).getAttribute("menuId").substring(0, 3));
				elementList.get(itemPosition).appendChild(
						elementList.get(itemPosition1)).appendChild(
						elementList.get(m));
				rootElement.appendChild(elementList.get(itemPosition));
			}
			if (elementList.get(m).getAttribute("menuId").length() == 3) {
				int itemPosition = searchElement(elementList, elementList
						.get(m).getAttribute("menuId").substring(0, 2));
				elementList.get(itemPosition).appendChild(elementList.get(m));
				rootElement.appendChild(elementList.get(itemPosition));
			}
			if (elementList.get(m).getAttribute("menuId").length() == 2) {
				rootElement.appendChild(elementList.get(m));
			}

		}

		DOMSource domSource = new DOMSource(doc);
		TransformerFactory tf = TransformerFactory.newInstance();
		Transformer transformer = null;

		try {
			transformer = tf.newTransformer();
			transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION,
					"yes");
			transformer.setOutputProperty(OutputKeys.METHOD, "xml");
			transformer.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-1");
			sw = new StringWriter();
			StreamResult sr = new StreamResult(sw);
			try {
				transformer.transform(domSource, sr);
			} catch (TransformerException e4) {
				System.out.println("The Problem4: " + e4);
			}

		} catch (Exception e6) {
			System.out.println("The Problem6: " + e6);
		}
		return sw;
	}

	private int searchElement(List<Element> elementList, String searchMenuId) {
		int index = 0;
		for (int i = 0; i < elementList.size(); i++) {
			if (elementList.get(i).getAttribute("menuId").equalsIgnoreCase(
					searchMenuId)) {
				break;
			}
			index++;
		}
		return index;
	}

	private boolean checkDuplicateElement(List<String> createdElement,
			String newMenuId) {

		boolean check = false;
		for (int i = 0; i < createdElement.size(); i++) {
			if (createdElement.get(i).equalsIgnoreCase(newMenuId)) {
				check = true;
				break;
			}
		}
		return check;
	}

	public boolean updateLogDetails(LoginInfoBean infoBean) {

		boolean flag = false;
		int i;

		try {
			i = getSqlMapClient().update("loginDetails.updatelastlogintime", infoBean);

			if (i == 1) {
				flag = true;
			}

		} catch (SQLException e) {
			System.out.println(e);
		}

		return flag;
	}

}
